package com.ie.cloud.payment.service.impl.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ie.cloud.payment.constants.BizStatus;
import com.ie.cloud.payment.dto.event.PushPayInfoMsgEvent;
import com.ie.cloud.payment.entity.MchApp;
import com.ie.cloud.payment.entity.PayOrder;
import com.ie.cloud.payment.exception.BizException;
import com.ie.cloud.payment.mapper.MchAppMapper;
import com.ie.cloud.payment.service.impl.PayOrderService;
import com.ie.cloud.payment.vo.PayOrderPartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import static com.ie.cloud.payment.service.impl.listener.CallbackMessageListenerService.parseFromJson;

/**
 * Created with FR
 *
 * @Author: DQ
 * @Date: 2025/07/24/11:05
 * @Description: 描述语句
 */
@Service
@Slf4j
public class PushPayInfoMsgEventListenerService {

    /**
     * 异步处理线程池
     */
    private final static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);

    @Resource
    private MchAppMapper mchAppMapper;

    @Resource
    private PayOrderService payOrderService;

    /**
     * 监听推送消息事件 并通过http推送给商户
     *
     * @param event 事件
     */
    @EventListener
    public void subscribeMsgToPush(PushPayInfoMsgEvent event) {

        log.info("收到事件,事件名称tag{},事件内容 {}", event.eventTag(), event.getSource());

        log.info("开始处理事件=================>");

        scheduledThreadPool.submit(() -> {
            try {
                PayOrderPartVo payOrderPartVo = parseFromJson(event.getSource().toString());


                MchApp mchApp = mchAppMapper.selectOne(MchApp.gw().eq(MchApp::getAppId, payOrderPartVo.getAppId()));


                if (mchApp == null) {
                    log.error("商户应用不存在 {}", payOrderPartVo.getAppId());
                    throw new BizException(BizStatus.MERCHANT_DOES_NOT_EXIST);
                }
                if (StrUtil.isEmpty(mchApp.getCallbackUrl())) {
                    log.error("商户应用回调地址不存在 {}", payOrderPartVo.getAppId());
                    throw new BizException(BizStatus.MERCHANT_DOES_NOT_EXIST);
                }

                String msg = buildMsg(event.getSource().toString());


                HttpRequest.post(mchApp.getCallbackUrl()).body(msg).header("msg", event.getSource().toString()).executeAsync();


                log.info("处理完成=================>");
            } catch (Exception e) {
                log.error("监听推送消息事件 并通过http推送给商户 错误: {}", e.getMessage());
                throw new BizException(BizStatus.INTERNAL_ERROR);
            }
        });


    }


    String buildMsg (String msg) {

        try {
            PayOrderPartVo payOrderPartVo = parseFromJson(msg);
            String busiCode = payOrderPartVo.getBusiCode();//等同于payOrderId

            PayOrder one = payOrderService.getOne(new LambdaQueryWrapper<PayOrder>()
                    .eq(PayOrder::getPayOrderId, busiCode));

            JSONObject body = new JSONObject();


            body.put("billCode", one.getMchOrderNo());
            body.put("tradeOrderCode",one.getPayOrderId());
            body.put("paymentTime",String.format("%s %s", payOrderPartVo.getTrxDate(), payOrderPartVo.getTrxTime()));
            body.put("paymentAmount",payOrderPartVo.getPayAmount());
            body.put("paymentChannel",payOrderPartVo.getPaymentChannel());
            body.put("tradeType",payOrderPartVo.getTradeType());
            body.put("extra",payOrderPartVo.getExtra());

        } catch (Exception e) {
            log.error("监听推送消息事件 并通过http推送给商户 错误 : {}", e.getMessage());
            return msg;
        }

        return msg;
    }
}
